package TCP.TCP5;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient() throws IOException {
        //new 这个对象的时候就需要和服务器建立连接，就要知道服务器在哪
        socket = new Socket("127.0.0.1", 9090);
    }
    public void start() {
        //长连接，一个连接会处理N个请求和响应
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanSocket = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true) {
                //1.从控制台读入请求
                System.out.print("->");
                String request = scanner.next();
                //2.将请求发给客户端
                printWriter.println(request);
                //刷新缓存区，确保信息发送
                printWriter.flush();
                //3.从服务器读取响应
                String response = scanSocket.next();
                //4.打印响应
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
            TcpEchoClient client = new TcpEchoClient();
            client.start();
    }
}